package com.example.permission.service.impl;

import com.example.permission.entity.Role;
import com.example.permission.mapper.RoleMapper;
import com.example.permission.service.RoleService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class RoleServiceImpl implements RoleService {

    private final SqlSessionFactory sqlSessionFactory;

    public RoleServiceImpl(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }

    @Override
    public Role getRoleWithMenusById(Long roleId) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            RoleMapper mapper = session.getMapper(RoleMapper.class);
            return mapper.selectRoleWithMenusById(roleId);
        }
    }

    @Override
    public Role getRoleWithMenusByName(String roleName) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            RoleMapper mapper = session.getMapper(RoleMapper.class);
            return mapper.selectRoleWithMenusByName(roleName);
        }
    }

    @Override
    public List<Role> getRolesByPage(int page, int pageSize) {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            RoleMapper mapper = session.getMapper(RoleMapper.class);
            int offset = (page - 1) * pageSize;
            return mapper.selectRolesByPage(offset, pageSize);
        }
    }

    @Override
    public int getRoleCount() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            RoleMapper mapper = session.getMapper(RoleMapper.class);
            return mapper.countRoles();
        }
    }
}